import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@WebServlet("/download")
public class Download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应方式
        resp.setContentType("application/x-msdownload");
        String fileName = "1.png";
        resp.setHeader("Content-Disposition","attachment;filename="+fileName);

        // 获取输出流
        OutputStream os = resp.getOutputStream();
        String path = req.getServletContext().getRealPath("file\\下载.png");
        InputStream is = new FileInputStream(path);
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = is.read(bytes)) > 0){
            os.write(bytes,0,len);
        }
        is.close();;
        os.close();
    }
}
